<template>
  <div class="dashboard-container">
    <!-- 添加 Tab 切换 -->
    <el-card class="mb-20">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="table in tables"
          :key="table.id"
          :label="table.description"
          :name="table.name"
        />
      </el-tabs>
    </el-card>

    <!-- 添加字段选择器和限制字段 -->
    <el-card class="mb-20">
      <el-form :inline="true">
        <el-form-item label="统计字段" class="form-item-width">
          <el-select
            v-model="selectedFields"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            class="select-width"
            @change="handleFieldsChange"
          >
            <el-option
              v-for="field in tableFields"
              :key="field.field_id"
              :label="field.label"
              :value="field.field"
            />
          </el-select>
        </el-form-item>

        <!-- 添加限制字段选择 -->
        <el-form-item label="限制字段" class="form-item-width">
          <el-select
            v-model="selectedLimitField"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            clearable
            placeholder="请选择限制字段"
            class="select-width"
            @change="handleLimitFieldChange"
          >
            <el-option
              v-for="field in tableFields"
              :key="field.field_id"
              :label="field.label"
              :value="field.field"
            />
          </el-select>
        </el-form-item>

        <!-- 添加限制字段值选择 -->
        <el-form-item
          v-if="selectedLimitField && selectedLimitField.length > 0"
          label="限制值"
          class="form-item-width"
        >
          <div v-for="field in selectedLimitField" :key="field" class="mb-2">
            <el-select
              v-model="limitFieldValue[field]"
              clearable
              :placeholder="
                '请选择' +
                (tableFields.find(f => f.field === field)?.label || field) +
                '的值'
              "
              class="select-width"
              @change="handleLimitValueChange"
            >
              <el-option
                v-for="item in limitFieldOptions[field] || []"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="20">
      <el-col v-for="(field, index) in selectedFields" :key="field" :span="12">
        <el-card class="chart-card">
          <div class="chart-header">
            <el-radio-group
              v-model="chartTypes[field]"
              @change="
                value => handleChartTypeChange(String(value), field, index)
              "
            >
              <el-radio-button label="pie">饼图</el-radio-button>
              <el-radio-button label="bar">柱状图</el-radio-button>
              <el-radio-button label="line">折线图</el-radio-button>
              <el-radio-button label="radar">雷达图</el-radio-button>
            </el-radio-group>
          </div>
          <div :ref="el => (chartRefs[index] = el)" class="chart" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, reactive, watch } from "vue";
import * as echarts from "echarts";
import { getAllTable, getAllTableField, getCount } from "@/api";

interface TableInfo {
  id: number;
  name: string;
  description: string;
  created_at: string;
  updated_at: string;
  permission_pid: number;
  permission_query_id: number;
}

interface TableField {
  field_id: number;
  table_id: number;
  table_name: string;
  field: string;
  type: string;
  must: string;
  label: string;
}

// 定义本地存储的key前缀
const STORAGE_KEY_PREFIX = "charts_config_";

interface ChartConfig {
  selectedFields: string[];
  selectedLimitField: string[];
  limitFieldValue: Record<string, string>;
  chartTypes: Record<string, string>;
}

const tables = ref<TableInfo[]>([]);
const tableFields = ref<TableField[]>([]);
const activeTab = ref("");

// 从本地存储加载配置
const loadConfig = (tableName: string): ChartConfig | null => {
  const config = localStorage.getItem(STORAGE_KEY_PREFIX + tableName);
  return config ? JSON.parse(config) : null;
};

// 保存配置到本地存储
const saveConfig = () => {
  if (!activeTab.value) return;

  const config: ChartConfig = {
    selectedFields: selectedFields.value,
    selectedLimitField: selectedLimitField.value,
    limitFieldValue: limitFieldValue.value,
    chartTypes: chartTypes
  };
  localStorage.setItem(
    STORAGE_KEY_PREFIX + activeTab.value,
    JSON.stringify(config)
  );
};

// 初始化状态
const selectedFields = ref<string[]>(["sex", "nationality"]);
const selectedLimitField = ref<string[]>([]);
const limitFieldValue = ref<Record<string, string>>({});
const limitFieldOptions = ref<
  Record<string, { label: string; value: string }[]>
>({});
const chartTypes = reactive<Record<string, string>>({});

// 监听配置变化并保存
watch(
  [selectedFields, selectedLimitField, limitFieldValue, () => chartTypes],
  () => {
    saveConfig();
  },
  { deep: true }
);

const chartRefs = ref<any[]>([]);
let charts: echarts.ECharts[] = [];

// 获取所有表信息
const fetchTables = async () => {
  try {
    const response = await getAllTable();
    if (response.data) {
      tables.value = response.data;
      if (tables.value.length > 0) {
        // 设置初始表
        const initialTable = tables.value[0];
        activeTab.value = initialTable.name;

        // 加载该表的配置
        const savedConfig = loadConfig(initialTable.name);
        if (savedConfig) {
          selectedFields.value = savedConfig.selectedFields;
          selectedLimitField.value = savedConfig.selectedLimitField;
          limitFieldValue.value = savedConfig.limitFieldValue;
          Object.assign(chartTypes, savedConfig.chartTypes);
        }

        await fetchTableFields(initialTable.id);
      }
    }
  } catch (error) {
    console.error("获取表信息失败:", error);
  }
};

// 获取表字段信息
const fetchTableFields = async (tableId: number) => {
  try {
    const response = await getAllTableField({
      table_id: tableId,
      table_name: "",
      field_name: "",
      type: "",
      label: ""
    });
    if (response.data) {
      tableFields.value = response.data;
      await fetchAllStatistics(tableId);
    }
  } catch (error) {
    console.error("获取表字段失败:", error);
  }
};

// 获取限制字段的可选值
const fetchLimitFieldOptions = async (tableId: number, field: string) => {
  try {
    const response = await getCount({
      table_id: tableId,
      group_by: field
    });
    if (response.data) {
      limitFieldOptions.value[field] = response.data.map(item => ({
        label: item[field] || "未知",
        value: item[field] || ""
      }));
    }
  } catch (error) {
    console.error("获取限制字段选项失败:", error);
  }
};

// 处理限制字段变化
const handleLimitFieldChange = async (fields: string[]) => {
  Object.keys(limitFieldValue.value).forEach(field => {
    limitFieldValue.value[field] = "";
  });
  saveConfig(); // 保存配置
  fields.forEach(async field => {
    if (field) {
      const selectedTable = tables.value.find(t => t.name === activeTab.value);
      if (selectedTable) {
        await fetchLimitFieldOptions(selectedTable.id, field);
      }
    }
  });
  await refreshCharts();
};

// 处理限制值变化
const handleLimitValueChange = async () => {
  saveConfig(); // 保存配置
  await refreshCharts();
};

// 刷新所有图表
const refreshCharts = async () => {
  const selectedTable = tables.value.find(t => t.name === activeTab.value);
  if (selectedTable) {
    await fetchAllStatistics(selectedTable.id);
  }
};

// 获取所有选中字段的统计数据
const fetchAllStatistics = async (tableId: number) => {
  // 清除现有图表
  charts.forEach(chart => chart.dispose());
  charts = [];

  // 获取每个选中字段的统计数据
  for (const field of selectedFields.value) {
    try {
      // 构建基础查询参数
      const params: Record<string, any> = {
        table_id: tableId,
        group_by: field
      };

      // 添加所有已选择的限制字段值
      selectedLimitField.value.forEach(limitField => {
        if (limitFieldValue.value[limitField]) {
          params[limitField] = limitFieldValue.value[limitField];
        }
      });

      const response = await getCount(params);
      if (response.data) {
        const index = selectedFields.value.indexOf(field);
        updateChart(response.data, field, index);
      }
    } catch (error) {
      console.error(`获取${field}统计数据失败:`, error);
    }
  }
};

const handleTabClick = async (tab: any) => {
  const selectedTable = tables.value.find(t => t.name === tab.props.name);
  if (selectedTable) {
    // 保存当前表的配置
    saveConfig();

    // 切换到新表
    activeTab.value = selectedTable.name;

    // 加载新表的配置
    const savedConfig = loadConfig(selectedTable.name);
    if (savedConfig) {
      selectedFields.value = savedConfig.selectedFields;
      selectedLimitField.value = savedConfig.selectedLimitField;
      limitFieldValue.value = savedConfig.limitFieldValue;
      Object.assign(chartTypes, savedConfig.chartTypes);
    } else {
      // 如果没有保存的配置，使用默认值
      selectedFields.value = ["sex", "nationality"];
      selectedLimitField.value = [];
      limitFieldValue.value = {};
      Object.assign(chartTypes, {});
    }

    await fetchTableFields(selectedTable.id);
  }
};

// 字段多选变化处理
const handleFieldsChange = async () => {
  saveConfig(); // 保存配置
  const selectedTable = tables.value.find(t => t.name === activeTab.value);
  if (selectedTable) {
    await fetchAllStatistics(selectedTable.id);
  }
};

// 处理图表类型变化
const handleChartTypeChange = async (
  type: string,
  field: string,
  index: number
) => {
  chartTypes[field] = type;
  saveConfig(); // 保存配置
  const selectedTable = tables.value.find(t => t.name === activeTab.value);
  if (selectedTable) {
    // 构建基础查询参数
    const params: Record<string, any> = {
      table_id: selectedTable.id,
      group_by: field
    };

    // 添加所有已选择的限制字段值
    selectedLimitField.value.forEach(limitField => {
      if (limitFieldValue.value[limitField]) {
        params[limitField] = limitFieldValue.value[limitField];
      }
    });

    try {
      const response = await getCount(params);
      if (response.data) {
        updateChart(response.data, field, index, type);
      }
    } catch (error) {
      console.error(`获取${field}统计数据失败:`, error);
    }
  }
};

// 更新单个图表
const updateChart = (
  data: any[],
  field: string,
  index: number,
  chartType?: string
) => {
  if (!chartRefs.value[index]) return;

  // 使用已保存的图表类型或默认为饼图
  const type = chartType || chartTypes[field] || "pie";

  // 如果图表已存在，先销毁
  if (charts[index]) {
    charts[index].dispose();
  }

  const chart = echarts.init(chartRefs.value[index]);
  charts[index] = chart;

  const fieldLabel =
    tableFields.value.find(f => f.field === field)?.label || field;
  const tableName =
    tables.value.find(t => t.name === activeTab.value)?.description || "";
  let titleText = `${tableName} - 按${fieldLabel}统计`;

  // 如果有限制条件，在标题中显示
  if (selectedLimitField.value.length > 0) {
    const limitLabels = selectedLimitField.value
      .map(field => {
        const fieldInfo = tableFields.value.find(f => f.field === field);
        return fieldInfo?.label;
      })
      .filter(Boolean);
    const limitValues = selectedLimitField.value.map(
      field => limitFieldValue.value[field] || "未知"
    );
    titleText += `\n(${limitLabels.join(", ")}: ${limitValues.join(", ")})`;
  }

  // 生成随机颜色数组
  const colors = data.map(() => {
    const r = Math.floor(Math.random() * 200 + 55);
    const g = Math.floor(Math.random() * 200 + 55);
    const b = Math.floor(Math.random() * 200 + 55);
    return `rgb(${r},${g},${b})`;
  });

  // 准备数据
  const names = data.map(item => item[field] || "未知");
  const values = data.map(item => item.count);

  // 基础配置
  const baseOption: Record<string, any> = {
    title: {
      text: titleText,
      left: "center",
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: "normal"
      }
    },
    tooltip: {
      trigger: type === "pie" ? "item" : "axis",
      formatter: type === "pie" ? "{b}: {c} ({d}%)" : "{b}: {c}"
    },
    legend: {
      orient: type === "pie" ? "vertical" : "horizontal",
      right: type === "pie" ? 10 : "center",
      top: type === "pie" ? "center" : 40
    }
  };

  // 根据图表类型设置特定配置
  let seriesConfig: any = {};

  switch (type) {
    case "pie":
      seriesConfig = {
        type: "pie",
        radius: ["40%", "70%"],
        center: ["40%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: "{b}: {c}人"
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: "bold"
          }
        },
        data: data.map((item, index) => ({
          name: item[field] || "未知",
          value: item.count,
          itemStyle: { color: colors[index] }
        }))
      };
      break;

    case "bar":
      seriesConfig = {
        type: "bar",
        barWidth: "60%",
        data: values.map((value, index) => ({
          value,
          itemStyle: { color: colors[index] }
        }))
      };
      baseOption.xAxis = {
        type: "category",
        data: names,
        axisLabel: { interval: 0, rotate: 30 }
      };
      baseOption.yAxis = { type: "value" };
      break;

    case "line":
      seriesConfig = {
        type: "line",
        smooth: true,
        data: values.map((value, index) => ({
          value,
          itemStyle: { color: colors[index] }
        })),
        areaStyle: {}
      };
      baseOption.xAxis = {
        type: "category",
        data: names,
        axisLabel: { interval: 0, rotate: 30 }
      };
      baseOption.yAxis = { type: "value" };
      break;

    case "radar":
      const indicator = names.map(name => ({
        name,
        max: Math.max(...values) * 1.2
      }));
      baseOption.radar = {
        indicator,
        radius: "60%"
      };
      seriesConfig = {
        type: "radar",
        data: [
          {
            value: values,
            name: fieldLabel,
            itemStyle: { color: colors[0] },
            areaStyle: {
              color: colors[0],
              opacity: 0.6
            }
          }
        ]
      };
      break;
  }

  chart.setOption({
    ...baseOption,
    series: [seriesConfig]
  });
};

// 监听窗口大小变化
const handleResize = () => {
  charts.forEach(chart => chart.resize());
};

onMounted(() => {
  fetchTables();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
  charts.forEach(chart => chart.dispose());
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart {
  height: 400px;
}

/* 添加选择框宽度样式 */
.form-item-width {
  margin-right: 20px;
}

.select-width {
  width: 300px;
}

:deep(.el-select) {
  width: 200px;
}

:deep(.el-select .el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__content) {
  flex: 1;
  width: auto;
}

.chart-header {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}
</style>
